package com.snake

import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp

import com.common.MessageBox
import com.snake.Game.Status
import com.snake.ui.theme.SnakeTheme

// 主活动
class MainActivity: ComponentActivity() {
    private lateinit var mGame: Game                // 游戏
    private lateinit var mMessageBox: MessageBox    // 消息窗口

    /**
     * 界面布局。
     */
    @Composable
    fun Greeting() {
        // 初始化成员
        mMessageBox.Greeting()

        // 计算游戏区域尺寸
        val gameBoardWidthPx = resources.displayMetrics.widthPixels
        Const.GRID_SIZE = (gameBoardWidthPx / Const.GAME_BOARD_GRID_COUNT_H).toFloat()
        val density = LocalDensity.current.density
        val toolbarHeightPx = Const.GRID_SIZE * Const.MAIN_ACTIVITY_TOOLBAR_HEIGHT_MULTIPLE
        val toolbarHeightDp = toolbarHeightPx / density
        var gameBoardHeightDp by remember {
            mutableFloatStateOf(0f)
        }
        var statusBarHeightDp by remember {
            mutableFloatStateOf(0f)
        }

        // 布局
        Column(Modifier
            .fillMaxSize()
            .systemBarsPadding()
            .onSizeChanged { size ->
                Const.GAME_BOARD_GRID_COUNT_V =
                    ((size.height.toFloat() - toolbarHeightPx) / Const.GRID_SIZE - 1f).toInt()
                gameBoardHeightDp = (Const.GRID_SIZE * Const.GAME_BOARD_GRID_COUNT_V) / density
                statusBarHeightDp =
                    size.height.toFloat() / density - toolbarHeightDp - gameBoardHeightDp
            }
        ) {
            // 工具栏
            Row(Modifier
                .fillMaxWidth()
                .height(toolbarHeightDp.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // "开始"按钮
                IconButton(
                    onClick = onButtonStartClicked,
                    modifier = Modifier.padding(start = Const.MAIN_ACTIVITY_CTRL_PADDING)
                ) {
                    Image(BitmapFactory.decodeResource(resources, R.mipmap.button_start).asImageBitmap(), "")
                }
                // "暂停"按钮
                val btnPauseEnabled = mGame.status != Status.END
                val btnPauseImage = if (btnPauseEnabled) BitmapFactory.decodeResource(resources, R.mipmap.button_pause).asImageBitmap()
                    else BitmapFactory.decodeResource(resources, R.mipmap.button_pause_disabled).asImageBitmap()
                val btnPauseColor = if (mGame.status == Status.PAUSED) Color.LightGray else Color.Transparent
                IconButton(
                    onClick = onButtonPauseClicked,
                    enabled = btnPauseEnabled,
                    colors = IconButtonColors(btnPauseColor, btnPauseColor, btnPauseColor, btnPauseColor)
                ) {
                    Image(btnPauseImage, "")
                }
                // "播放音乐"按钮
                val btnMusicColor = if (mGame.isMusicEnabled) Color.LightGray else Color.Transparent
                IconButton(
                    onClick = onButtonMusicClicked,
                    colors = IconButtonColors(btnMusicColor, btnMusicColor, btnMusicColor, btnMusicColor)
                ) {
                    Image(BitmapFactory.decodeResource(resources, R.mipmap.button_play_music).asImageBitmap(), "")
                }
                // "帮助"按钮
                IconButton(
                    onClick = onButtonHelpClicked) {
                    Image(BitmapFactory.decodeResource(resources, R.mipmap.button_help).asImageBitmap(), "")
                }
            }

            // 游戏区域
            mGame.GameBoard(Modifier
                .fillMaxWidth()
                .height(gameBoardHeightDp.dp)
            )

            // 状态栏
            Row(modifier = Modifier
                .fillMaxWidth()
                .height(statusBarHeightDp.dp)
                .background(Const.MAIN_ACTIVITY_STATUS_BAR_COLOR),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = super.getString(R.string.IDS_DIFFICULTY, mGame.difficulty),
                    modifier = Modifier
                        .weight(0.5f)
                        .padding(start = Const.MAIN_ACTIVITY_CTRL_PADDING)
                )
                Text(
                    text = super.getString(R.string.IDS_SCORE, mGame.score),
                    modifier = Modifier
                        .weight(0.5f)
                        .padding(start = Const.MAIN_ACTIVITY_CTRL_PADDING)
                )
            }

            // 吐司窗口
            if (mGame.status == Status.WON) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_WON), Toast.LENGTH_LONG).show()
            } else if (mGame.status == Status.LOST) {
                Toast.makeText(this@MainActivity, super.getString(R.string.IDS_LOST), Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * "帮助"按钮的单击响应方法。
     */
    val onButtonHelpClicked = fun() {
        if (mGame.status == Status.PLAYING) {
            this.onButtonPauseClicked()
        }
        mMessageBox.show(tipText = super.getString(R.string.IDS_HELP_TEXT))
    }

    /**
     * "播放音乐"按钮的单击响应方法。
     */
    val onButtonMusicClicked = fun() {
        mGame.playMusic()
    }

    /**
     * "暂停"按钮的单击响应方法。
     */
    val onButtonPauseClicked = fun() {
        mGame.pause()
    }

    /**
     * "开始"按钮的单击响应方法。
     */
    val onButtonStartClicked = fun() {
        // 游戏开始
        mGame.start()
    }

    /**
     * 创建事件的响应方法。
     * @param savedInstanceState    保存的实例状态
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.enableEdgeToEdge()

        // 初始化成员
        mGame = Game(this)
        mMessageBox = MessageBox()

        // 设置内容
        this.setContent {
            SnakeTheme {
                Greeting()
            }
        }
    }

    /**
     * 暂停事件的响应方法。
     */
    public override fun onPause() {
        super.onPause()
        if (mGame.status == Status.PLAYING) {
            this.onButtonPauseClicked()
        }
    }
}
